#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from osmp.host.models import Product
from osmp.users.models import UserProfile, Authority
from django.contrib.auth.models import User
from osmp.document.models import Doc,Comment
from osmp.util import commom
from osmp import settings
import time

def doc(request): 
    return HttpResponseRedirect('/doc/list/1/')

def doc_list(request, id): 
    auth_pids = request.session['auth_pids']
    tree = ""  
    tree = commom.creatree(-1, tree, '/doc/list/', '', False, auth_pids = auth_pids)
    if request.method == 'POST':
        upfile = request.FILES.get('file', None)

        if upfile:
            localname = "%s.%d" % (upfile.name, time.time())
            path = "%s/%s" % (settings.UPLOAD_PATH, localname)
            fd = open(path, "w")
            fd.write(upfile.read())
            fd.close()
        else:
            return Http404

        pid = Product.objects.get(id = id)
        if not pid:
            return Http404

        Doc.objects.create( pid = pid,
                            uid = request.user,
                            type = '0',
                            name = localname
                            )       
        return HttpResponseRedirect('/doc/list/%s/' % id)
    else:
#        if id == '1':
#            docs = Doc.objects.filter(pid__in = auth_pids)
#        else:
#            docs = Doc.objects.filter(pid = id)
        docs = Doc.objects.all()
        username = request.user
        print username
        return render_to_response('doclist.html', locals())

import datetime,re
def adddoc(request):
    errors = []
    messages = []
    #根据请求方式判断操作
    if request.method == 'POST':
        if not request.POST.get('title', ''):
            errors.append('请输入文档标题')
        if not request.POST.get('text', ''):
            errors.append('请输入文档内容')
        if not request.POST.get('type', ''):
            errors.append('请选择产品线')
        if not request.POST.get('pid', ''):
            errors.append('请选择产品线')
        if errors:
            #验证未通过 - 返回错误提示信息
            return render_to_response("doclist.html",locals())
        if not errors:
            text = request.POST.get('text')
            text = text.replace('\r','')
            text = text.replace('\n','')
            text = text.replace('\t','')
#            text = re.match(r'(\w+) (\w+)(?P<sign>.*)', text)
            #print text
            Doc.objects.create(
                    name = request.POST.get('title'),
                    context = text,
                    type = request.POST.get('type'),
                    uid = User.objects.get(id = request.user.id),
                    pid = Product.objects.get(id = request.POST.get('pid','')),
                    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                )
            return render_to_response( "doclist.html",locals())
    else:
        return render_to_response("adddoc.html",locals())

def show(request,id):
    doc = Doc.objects.get(id = id)
    clist = Comment.objects.filter(did = id).order_by("timestamp")
    if not clist:
        clist = []
    username = request.user

    return render_to_response( "docshow.html",locals())

def edit(request,id):
    errors = []
    messages = []
    if request.method == 'POST':
        if not request.POST.get('title', ''):
            errors.append('请输入文档标题')
        if not request.POST.get('text', ''):
            errors.append('请输入文档内容')
        if not request.POST.get('type', ''):
            errors.append('请选择产品线')
        if not request.POST.get('pid', ''):
            errors.append('请选择产品线')
        if errors:
            #验证未通过 - 返回错误提示信息
            return render_to_response("doclist.html",locals())
        if not errors:
            Doc.objects.get(id=id).update(
                title=request.POST.get('title'),
                text=request.POST.get('text'),
                type=request.POST.get('type'),
                pid=request.POST.get('pid')
            )
            message = "信息更新成功"
            return render_to_response("doclist.html",locals())            
    else:
        doc = Doc.objects.get(id = id)
        return render_to_response( "docedit.html",locals())

def de(request,id):
    messages = []
    if id:
        doc = Doc.objects.get(id = id)
        doc.delete()
        clist = Comment.objects.filter(did = id)
        clist.delete()
        messages.append("监控删除成功")
        
def comment(request):
    errors = []
    messages = []
#    print request.POST.get('score')
#    print request.POST.get('content')
#    print request.user
    #根据请求方式判断操作
    if request.method == 'POST':
        if not request.POST.get('content', ''):
            errors.append('请输入评审内容')
        if not request.POST.get('id', ''):
            errors.append('未获取到文档id信息')
        if not request.POST.get('status', ''):
            errors.append('请选择是否通过')
        if errors:
            #验证未通过 - 返回错误提示信息
            id = request.POST.get('id')
            doc = Doc.objects.get(id = id)
            clist = Comment.objects.filter(did = id).order_by("timestamp")
            username = request.user
            errors
            return render_to_response( "docshow.html",locals())
        if not errors:
            Comment.objects.create(
                did = Doc.objects.get(id = request.POST.get('id')),
                uid = request.user,
#                score = request.POST.get('score'),
                record = request.POST.get('status'),
                content = request.POST.get('content'),
                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )
            print request.POST.get('id')
            print request.POST.get('status')
            Doc.objects.filter(id = request.POST.get('id')).update(
                status = request.POST.get('status')
            )
            return HttpResponseRedirect("/doc")
    else:
        return HttpResponseRedirect("/doc/show")
